package com.ww.idiom.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;

import com.ww.core.activity.MyActivity;
import com.ww.core.widget.dialog.MsgDialog;
import com.ww.core.widget.edittext.SearchEditText;
import com.ww.idiom.R;
import com.ww.idiom.adapter.MainAdapter;
import com.ww.idiom.db.IdiomDbHelper;

/**
 * @since 
 * @version 2013-12-13
 * @author wangwei
 */
public class QueryActivity extends MyActivity {
	private ArrayList<String> list = new ArrayList<String>();
	private ListView listview;
	private SearchEditText searchEditText;
	private Button button;
	private MainAdapter mainAdapter;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_query);
		setTitle("搜索");
		listview = (ListView) findViewById(R.id.listView);
		ImageButton back = (ImageButton) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		searchEditText = (SearchEditText) findViewById(R.id.search_Keywords);
		button = (Button) findViewById(R.id.button_search);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				getDetail();
			}
		});

		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent in = new Intent(QueryActivity.this, ResultActivity.class);
				in.putExtra("index", arg2);
				in.putStringArrayListExtra("list", list);
				startActivity(in);
			}
		});
	}

	/**
	 * 鑾峰彇鏂伴椈璇︽�?
	 * @param id 鏂伴椈id
	 */
	public void getDetail() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				IdiomDbHelper s = new IdiomDbHelper(QueryActivity.this);
				list = s.query(searchEditText.getText().toString());
				handler.sendEmptyMessage(1);
			}
		}).start();
	}

	// 瀹氫箟涓�釜Handler锛岀敤鏉ュ紓姝ュ鐞嗘暟鎹�
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (list.size() > 0) {
				mainAdapter = new MainAdapter(QueryActivity.this, list);
				listview.setAdapter(mainAdapter);
			} else {
				MsgDialog.show(QueryActivity.this, "没有查询到任何结果");
			}
		};
	};

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}